<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { Modal, Tree } from 'ant-design-vue';
import { ArrowLeftOutlined, PlusOutlined, ReloadOutlined, SettingOutlined } from '@ant-design/icons-vue';
import {
  createProductModelMapping,
  createProductModelMappingWithDataSet,
  deleteProductModelMapping,
  fetchModels,
  fetchProductModelMappings,
  fetchProductModelMappingsByDataSetId,
  fettchProductDefinitions,
  getProductIdByClassName,
  updateProductModelMapping
} from '@/service/api/valuation';

// 路由相关
const route = useRoute();
const router = useRouter();

// 映射集相关状态
const mappingSetId = ref<string | null>(null);
const mappingSetName = ref<string>('');
const isDetailMode = ref(false);

// 数据状态
const loading = ref(false);
const treeData = ref<any[]>([]);
const selectedProduct = ref<Api.Valuation.ProductDefinition | null>(null);
const expandedKeys = ref<string[]>([]);

// 产品映射状态管理
const productMappingStatus = ref<Record<string, boolean>>({});

// 模型相关状态
const modelLoading = ref(false);
const modelList = ref<any[]>([]);
const selectedModelId = ref<number | null>(null);
const existingMappings = ref<Api.Valuation.ProductModelRelation[]>([]);

// 模型配置相关状态
const configModalVisible = ref(false);
const configModalLoading = ref(false);
const currentModelConfig = ref<any>(null);
const showConfigForm = ref(false);
// 当前正在编辑的映射ID（用于区分更新与新增）
const editingMappingId = ref<number | null>(null);

// 模型配置表单数据
const modelConfigForm = ref({
  modelId: undefined as number | undefined,
  modelName: '',
  solver: '',
  parameters: {} as Record<string, any>,
  isDefault: false
});

// 求解器选项
const solverOptions = [
  { value: 'ANALYTICAL', label: '解析解', description: '使用数学公式直接计算，速度快，精度高' },
  { value: 'MONTE_CARLO', label: '蒙特卡洛解', description: '使用随机模拟方法，适用于复杂产品' },
  { value: 'BINOMIAL_TREE', label: '二叉树解', description: '使用二叉树方法，适用于美式期权' },
  { value: 'PDE', label: '偏微分方程解', description: '使用有限差分方法求解PDE' }
];

// 根据求解器显示不同的参数配置
const parameterFields = computed(() => {
  const solver = modelConfigForm.value.solver;
  const fields: any[] = [];

  switch (solver) {
    case 'MONTE_CARLO':
      fields.push(
        {
          key: 'pathNumber',
          label: '路径数量',
          type: 'number',
          default: 10000,
          min: 1000,
          max: 1000000,
          description: '蒙特卡洛模拟的路径数量，越多精度越高但计算越慢'
        },
        {
          key: 'stepNumber',
          label: '时间步数',
          type: 'number',
          default: 100,
          min: 10,
          max: 1000,
          description: '时间离散化的步数'
        },
        {
          key: 'randomSeed',
          label: '随机种子',
          type: 'number',
          default: 12345,
          min: 1,
          description: '随机数生成器种子，用于结果重现'
        },
        {
          key: 'useAntithetic',
          label: '使用对偶变量',
          type: 'boolean',
          default: false,
          description: '使用对偶变量减少方差'
        },
        {
          key: 'useControlVariate',
          label: '使用控制变量',
          type: 'boolean',
          default: false,
          description: '使用控制变量提高精度'
        }
      );
      break;
    case 'BINOMIAL_TREE':
      fields.push(
        {
          key: 'treeSteps',
          label: '树的步数',
          type: 'number',
          default: 100,
          min: 10,
          max: 1000,
          description: '二叉树的时间步数'
        },
        {
          key: 'treeType',
          label: '树的类型',
          type: 'select',
          default: 'CRR',
          options: [
            { value: 'CRR', label: 'Cox-Ross-Rubinstein' },
            { value: 'JR', label: 'Jarrow-Rudd' },
            { value: 'TIAN', label: 'Tian' }
          ],
          description: '二叉树构造方法'
        }
      );
      break;
    case 'PDE':
      fields.push(
        {
          key: 'spaceSteps',
          label: '空间网格数',
          type: 'number',
          default: 100,
          min: 50,
          max: 500,
          description: '空间方向的网格点数'
        },
        {
          key: 'timeSteps',
          label: '时间网格数',
          type: 'number',
          default: 100,
          min: 50,
          max: 500,
          description: '时间方向的网格点数'
        },
        {
          key: 'boundaryCondition',
          label: '边界条件',
          type: 'select',
          default: 'DIRICHLET',
          options: [
            { value: 'DIRICHLET', label: 'Dirichlet边界条件' },
            { value: 'NEUMANN', label: 'Neumann边界条件' }
          ],
          description: 'PDE求解的边界条件类型'
        }
      );
      break;
    case 'ANALYTICAL':
      break;
    default:
      break;
  }

  return fields;
});

/**
 * 功能：打开模型参数配置表单。
 *
 * - 若未传入 modelId，进入新增模式，重置表单；
 * - 若传入 modelId，加载该模型在当前映射集和产品下的已保存参数，进入编辑模式。
 */
function configureModelParameters(modelId?: number) {
  // 如果没有传入modelId，则打开模型选择配置模态框
  if (!modelId) {
    if (!selectedProduct.value) {
      window.$message?.error('请先选择产品');
      return;
    }

    // 直接打开配置表单，让用户选择模型
    currentModelConfig.value = null;
    showConfigForm.value = true;
    editingMappingId.value = null; // 新增模式，清空编辑状态

    // 重置表单
    modelConfigForm.value = {
      modelId: undefined,
      modelName: '',
      solver: '',
      parameters: {},
      isDefault: false
    };
    return;
  }

  // 如果传入了modelId，则查找对应的模型
  const model = modelList.value.find(m => m.id === modelId);
  if (!model) {
    window.$message?.error('模型不存在');
    return;
  }

  // 查找现有的映射关系，获取已配置的求解器和参数
  const existingMapping = existingMappings.value.find(m => m.modelId === modelId);
  let solver = '';
  let parameters = {};

  if (existingMapping) {
    // 记录当前编辑的映射ID
    editingMappingId.value = existingMapping.id as number;

    // 优先从solver字段获取求解器信息
    if (existingMapping.solver) {
      solver = existingMapping.solver;
    }

    // 优先从solverParams字段获取参数信息
    if (existingMapping.solverParams) {
      try {
        parameters = JSON.parse(existingMapping.solverParams);
      } catch (error) {
        console.warn('解析solverParams失败:', error);
      }
    }

    // 如果solver或parameters为空，尝试从configParams中获取
    if (!solver || Object.keys(parameters).length === 0) {
      const configParams = parseConfigParams(existingMapping.configParams);
      if (configParams) {
        if (!solver && configParams.solver) {
          solver = configParams.solver;
        }
        if (Object.keys(parameters).length === 0 && configParams.parameters) {
          parameters = configParams.parameters;
        }
      }
    }
  }

  currentModelConfig.value = model;
  showConfigForm.value = true;

  // 设置表单数据，包含已配置的求解器和参数
  modelConfigForm.value = {
    modelId: model.id,
    modelName: model.name,
    solver,
    parameters,
    isDefault: false
  };
}

// 当模型改变时，更新模型名称
function onModelChange(value: any) {
  const modelId = value as number;
  const model = modelList.value.find(m => m.id === modelId);
  if (model) {
    modelConfigForm.value.modelName = model.name;
  }
}

// 当模型或求解器改变时，重置参数
function onModelOrSolverChange() {
  modelConfigForm.value.parameters = {};
  // 设置默认参数值
  parameterFields.value.forEach(field => {
    if (field.default !== undefined) {
      modelConfigForm.value.parameters[field.key] = field.default;
    }
  });
}

// 保存模型配置
async function handleSaveConfig() {
  if (!selectedProduct.value) {
    window.$message?.error('请先选择产品');
    return;
  }

  // 验证必填字段
  if (!modelConfigForm.value.modelId) {
    window.$message?.error('请选择模型');
    return;
  }
  if (!modelConfigForm.value.solver) {
    window.$message?.error('请选择求解器');
    return;
  }

  // 验证参数
  for (const field of parameterFields.value) {
    const value = modelConfigForm.value.parameters[field.key];
    if (field.type === 'number' && value !== undefined) {
      if (field.min !== undefined && value < field.min) {
        window.$message?.error(`${field.label}不能小于${field.min}`);
        return;
      }
      if (field.max !== undefined && value > field.max) {
        window.$message?.error(`${field.label}不能大于${field.max}`);
        return;
      }
    }
  }

  configModalLoading.value = true;
  try {
    // 根据ProductDefinition类名获取对应的产品ID
    const response = await getProductIdByClassName(selectedProduct.value.className);
    let productId: number;

    if (response && typeof response === 'object' && 'data' in response) {
      productId = (response as any).data[0].id;
    } else {
      window.$message?.error('无法获取产品ID，请稍后重试');
      return;
    }

    if (!productId) {
      window.$message?.error('无法获取产品ID，请稍后重试');
      return;
    }

    // 检查是否已存在相同的产品-模型映射
    const currentMappings = existingMappings.value;
    const isDuplicate = currentMappings.some(
      (mapping: Api.Valuation.ProductModelRelation) =>
        mapping.productId === productId && mapping.modelId === modelConfigForm.value.modelId
    );

    if (isDuplicate && !currentModelConfig.value) {
      // 如果是新建配置且存在重复，给出提示
      Modal.confirm({
        title: '确认操作',
        content: '该产品已配置过此模型，是否要更新现有配置？',
        onOk: async () => {
          // 继续执行保存逻辑
          await proceedWithSave(productId, isDuplicate);
        }
      });
      return;
    }

    await proceedWithSave(productId, isDuplicate);
  } catch (error) {
    console.error('保存模型配置失败:', error);
    window.$message?.error('保存模型配置失败');
  } finally {
    configModalLoading.value = false;
  }

  /**
   * 功能：执行保存逻辑。
   *
   * - 若处于编辑模式（editingMappingId存在）则更新该映射；
   * - 若是新增且发现重复（当前映射集内已有相同 productId+modelId），则更新该记录；
   * - 否则正常新增，确保新增时包含 dataSetId 以实现配置隔离。
   */
  async function proceedWithSave(productId: number, isDuplicate: boolean) {
    // 构建配置参数
    const configParams = {
      solver: modelConfigForm.value.solver,
      parameters: modelConfigForm.value.parameters
    };

    // 1) 优先编辑已有记录
    let updateId = editingMappingId.value;

    // 2) 若新增但发现重复，则转换为更新当前映射集下的那条记录
    if (!updateId && isDuplicate) {
      const dup = existingMappings.value.find(
        (m: Api.Valuation.ProductModelRelation) =>
          m.productId === productId && m.modelId === modelConfigForm.value.modelId
      );
      updateId = dup?.id ?? null;
    }

    if (updateId) {
      // 走更新接口，确保只更新当前映射集内的该条记录
      await updateProductModelMapping(updateId, {
        configParams: JSON.stringify(configParams),
        isDefault: modelConfigForm.value.isDefault
      });
    } else {
      // 新增时，包含 dataSetId，防止不同映射集之间共享/覆盖
      const mappingData: any = {
        productId,
        modelId: modelConfigForm.value.modelId!,
        configParams: JSON.stringify(configParams),
        // 兼容后端可能会存储 solver 与 solverParams 字段
        solver: modelConfigForm.value.solver,
        solverParams: JSON.stringify(modelConfigForm.value.parameters),
        isDefault: modelConfigForm.value.isDefault
      };

      if (mappingSetId.value) {
        await createProductModelMappingWithDataSet({
          ...mappingData,
          dataSetId: mappingSetId.value
        });
      } else {
        await createProductModelMapping(mappingData);
      }
    }

    window.$message?.success(updateId ? '模型配置更新成功' : '模型配置保存成功');
    showConfigForm.value = false;
    editingMappingId.value = null;

    // 重新加载映射关系
    if (selectedProduct.value) {
      await loadProductModelMappings(selectedProduct.value.className);
      // 更新产品映射状态
      productMappingStatus.value[selectedProduct.value.className] = true;
    }
  }
}

// 保存模型配置（兼容旧的函数名）
const handleSaveModelConfig = handleSaveConfig;

/** 功能：进入新增配置模式，清空编辑状态与表单。 */
function showConfigurationForm() {
  showConfigForm.value = true;
  editingMappingId.value = null; // 新增模式，清空编辑状态
  // 重置表单
  modelConfigForm.value = {
    modelId: undefined,
    modelName: '',
    solver: '',
    parameters: {},
    isDefault: false
  };
  currentModelConfig.value = null;
}

/** 功能：取消当前配置编辑，关闭表单并清空编辑状态。 */
function handleCancelConfig() {
  showConfigForm.value = false;
  configModalVisible.value = false;
  currentModelConfig.value = null;
  editingMappingId.value = null; // 清空编辑状态
  modelConfigForm.value = {
    modelId: undefined,
    modelName: '',
    solver: '',
    parameters: {},
    isDefault: false
  };
}

// 解析配置参数
function parseConfigParams(configParams: string | null | undefined): any {
  if (!configParams) return null;
  try {
    return JSON.parse(configParams);
  } catch {
    return null;
  }
}

// 批量加载产品映射状态
async function loadAllProductMappingStatus(products: Api.Valuation.Product[]) {
  const statusPromises = products.map(async product => {
    try {
      // 根据产品类名获取产品ID
      const productIdResponse = (await getProductIdByClassName(product.className)).data;
      let productId: number;

      if (productIdResponse && typeof productIdResponse === 'object') {
        if ((productIdResponse as any)[0] !== undefined) {
          productId = (productIdResponse as any)[0].id;
        } else {
          return { className: product.className, hasMappings: false };
        }
      } else {
        return { className: product.className, hasMappings: false };
      }

      // 根据映射集ID获取产品的模型映射关系
      let mappingsResponse;
      if (mappingSetId.value) {
        // 如果有映射集ID，按映射集ID过滤
        mappingsResponse = await fetchProductModelMappingsByDataSetId(mappingSetId.value, productId);
      } else {
        // 如果没有映射集ID，获取所有映射关系
        mappingsResponse = await fetchProductModelMappings(productId);
      }

      let mappings: Api.Valuation.ProductModelRelation[] = [];

      if (Array.isArray(mappingsResponse)) {
        mappings = mappingsResponse;
      } else if (mappingsResponse && Array.isArray(mappingsResponse.data)) {
        mappings = mappingsResponse.data;
      }

      return { className: product.className, hasMappings: mappings.length > 0 };
    } catch (error) {
      console.warn(`获取产品 ${product.className} 映射状态失败:`, error);
      return { className: product.className, hasMappings: false };
    }
  });

  const results = await Promise.all(statusPromises);
  const statusMap: Record<string, boolean> = {};

  results.forEach(result => {
    statusMap[result.className] = result.hasMappings;
  });

  productMappingStatus.value = statusMap;
}

// 初始化映射集信息
function initMappingSetInfo() {
  const queryMappingSetId = route.query.mappingSetId as string;
  const queryMappingSetName = route.query.mappingSetName as string;

  if (queryMappingSetId) {
    mappingSetId.value = queryMappingSetId;
    mappingSetName.value = queryMappingSetName || `映射集 ${queryMappingSetId}`;
    isDetailMode.value = true;
    console.log('🔗 进入映射集详情模式:', {
      id: mappingSetId.value,
      name: mappingSetName.value
    });
  } else {
    isDetailMode.value = false;
    console.log('🌲 普通产品树模式');
  }
}

// 返回映射集列表
function goBackToMappingList() {
  router.push('/valuation/product-model-mapping');
}

// 加载产品树
async function loadProductTree() {
  try {
    loading.value = true;
    console.log('🌲 开始加载产品树...');

    let productData: Api.Valuation.Product[] = [];

    try {
      const response = await fettchProductDefinitions();
      if (response && Array.isArray(response)) {
        productData = response;
      } else if (response?.data && Array.isArray(response.data)) {
        productData = response.data;
      }
    } catch (fetchError) {
      throw new Error(fetchError instanceof Error ? fetchError.message : '加载产品树失败');
    }

    console.log('🌲 数据条数:', productData.length);

    if (Array.isArray(productData) && productData.length > 0) {
      // 按分类分组产品定义
      const categoryGroups = productData.reduce(
        (groups, item) => {
          const category = item.categoryType || item.category || '其他';
          if (!groups[category]) {
            groups[category] = [];
          }
          groups[category].push({
            ...item,
            key: item.className,
            title: item.className,
            isLeaf: true
          });
          return groups;
        },
        {} as Record<string, any[]>
      );

      // 构建树形结构
      const treeNodes = Object.keys(categoryGroups).map(category => ({
        key: category,
        title: category,
        className: category,
        category,
        fullClassName: '',
        packageName: '',
        categoryKey: category,
        description: `${category}类产品`,
        fieldCount: categoryGroups[category].length,
        isLeaf: false,
        children: categoryGroups[category]
      }));

      treeData.value = treeNodes;

      // 加载所有产品的映射状态
      await loadAllProductMappingStatus(productData);
    } else {
      console.warn('🌲 没有获取到有效的产品树数据');
      treeData.value = [];
    }
  } catch (error) {
    console.error('🌲 加载产品树失败:', error);
    window.$message?.error('加载产品树失败');
    treeData.value = [];
  } finally {
    loading.value = false;
  }
}

// 展开所有节点
function expandAll() {
  const getAllKeys = (data: any[]): string[] => {
    const keys: string[] = [];
    data.forEach(item => {
      keys.push(item.key);
      if (item.children && item.children.length > 0) {
        keys.push(...getAllKeys(item.children));
      }
    });
    return keys;
  };
  expandedKeys.value = getAllKeys(treeData.value);
}

// 收起所有节点
function collapseAll() {
  expandedKeys.value = [];
}

// 处理节点展开/收起
function onExpand(keys: any[]) {
  expandedKeys.value = keys.map(key => key.toString());
}

// 根据模型ID获取模型名称
function getModelNameById(modelId: number): string {
  const model = modelList.value.find(m => m.id === modelId);
  return model ? model.name : `模型ID: ${modelId}`;
}

// 删除产品模型映射关系
async function removeProductModelMapping(mapping: Api.Valuation.ProductModelRelation) {
  if (!mapping.id) {
    window.$message?.error('映射关系ID不存在');
    return;
  }

  try {
    await deleteProductModelMapping(mapping.id);
    window.$message?.success(`成功解除模型 "${getModelNameById(mapping.modelId)}" 的绑定`);

    // 重新加载映射关系
    if (selectedProduct.value) {
      await loadProductModelMappings(selectedProduct.value.className);
      // 更新产品映射状态
      productMappingStatus.value[selectedProduct.value.className] = existingMappings.value.length > 0;
    }
  } catch (error: any) {
    console.error('📋 删除产品模型映射失败:', error);
    const errorMessage = error?.response?.data?.msg || error?.message || '未知错误';
    window.$message?.error(`删除映射关系失败: ${errorMessage}`);
  }
}

// 树节点选择
function onTreeSelect(selectedKeys: any[], info: any) {
  if (selectedKeys.length > 0 && info.node) {
    selectedProduct.value = info.node;
  } else {
    selectedProduct.value = null;
  }
}

// 扫描产品实体类
async function handleScanProducts() {
  try {
    loading.value = true;
    console.log('🔍 开始扫描产品实体类...');
    const response = await fettchProductDefinitions();

    let scannedProducts: Api.Valuation.Product[] = [];
    if (response && Array.isArray(response)) {
      scannedProducts = response;
    } else if (response?.data && Array.isArray(response.data)) {
      scannedProducts = response.data;
    }

    window.$message?.success(`成功扫描到 ${scannedProducts.length} 个产品实体类`);

    // 扫描完成后重新加载产品树
    await loadProductTree();
  } catch (error) {
    console.error('🔍 扫描产品实体类失败:', error);
    window.$message?.error('扫描产品实体类失败');
  } finally {
    loading.value = false;
  }
}

// 加载模型列表
async function loadModels() {
  try {
    modelLoading.value = true;
    const response = await fetchModels();
    if (response && Array.isArray(response)) {
      modelList.value = response;
    } else if (response?.data && Array.isArray(response.data)) {
      modelList.value = response.data;
    }
  } catch (error) {
    console.error('📋 加载模型列表失败:', error);
    window.$message?.error('加载模型列表失败');
  } finally {
    modelLoading.value = false;
  }
}

// 加载产品模型映射关系
async function loadProductModelMappings(productClassName: string) {
  if (!productClassName) return;

  try {
    console.log('📋 开始加载产品模型映射关系:', productClassName);

    // 根据产品类名获取产品ID
    const productIdResponse = (await getProductIdByClassName(productClassName)).data;
    let productId: number;

    if (productIdResponse && typeof productIdResponse === 'object') {
      if ((productIdResponse as any)[0] !== undefined) {
        productId = (productIdResponse as any)[0].id;
      } else {
        return;
      }
    } else {
      console.warn('📋 无法获取产品ID，响应格式异常:', productIdResponse);
      window.$message?.error('无法获取产品ID，请检查产品是否存在');
      existingMappings.value = [];
      selectedModelId.value = null;
      return;
    }

    if (!productId) {
      console.warn('📋 产品ID为空，清空映射关系');
      window.$message?.warning('产品ID为空，无法加载模型映射关系');
      existingMappings.value = [];
      selectedModelId.value = null;
      return;
    }

    console.log('📋 获取到产品ID:', productId, '开始获取模型映射关系');

    // 根据映射集ID和产品ID获取模型映射关系
    let mappingsResponse;
    if (mappingSetId.value) {
      // 如果有映射集ID，按映射集ID过滤
      mappingsResponse = await fetchProductModelMappingsByDataSetId(mappingSetId.value, productId);
    } else {
      // 如果没有映射集ID，获取所有映射关系
      mappingsResponse = await fetchProductModelMappings(productId);
    }

    let mappings: Api.Valuation.ProductModelRelation[] = [];

    if (Array.isArray(mappingsResponse)) {
      mappings = mappingsResponse;
    } else if (mappingsResponse && Array.isArray(mappingsResponse.data)) {
      mappings = mappingsResponse.data;
    }

    existingMappings.value = mappings;
    selectedModelId.value = mappings.length > 0 ? mappings[0].modelId : null;
  } catch (error: any) {
    console.error('📋 加载产品模型映射失败:', error);
    const errorMessage = error?.response?.data?.msg || error?.message || '未知错误';
    window.$message?.error(`加载产品模型映射失败: ${errorMessage}`);
    existingMappings.value = [];
    selectedModelId.value = null;
  }
}

// 监听选中产品变化，加载对应的模型映射
watch(selectedProduct, newProduct => {
  // 重置所有相关状态
  selectedModelId.value = null;
  existingMappings.value = [];
  showConfigForm.value = false;
  currentModelConfig.value = null;

  // 重置模型配置表单
  modelConfigForm.value = {
    modelId: undefined,
    modelName: '',
    solver: '',
    parameters: {},
    isDefault: false
  };

  if (newProduct && newProduct.className && (newProduct as any).isLeaf !== false) {
    loadProductModelMappings(newProduct.className);
  }
});

// 监听路由参数变化
watch(
  () => route.query,
  (newQuery, oldQuery) => {
    // 当mappingSetId参数发生变化时，重新初始化
    if (newQuery.mappingSetId !== oldQuery?.mappingSetId) {
      console.log('🔄 路由参数变化，重新初始化映射集信息');
      initMappingSetInfo();
      loadProductTree();
    }
  },
  { immediate: false }
);

onMounted(() => {
  initMappingSetInfo();
  loadProductTree();
  loadModels();
});
</script>

<template>
  <div class="product-tree-management">
    <!-- 映射集信息头部 -->
    <ACard v-if="isDetailMode" class="mb-4">
      <div class="flex items-center justify-between">
        <div class="flex items-center gap-3">
          <AButton type="text" @click="goBackToMappingList">
            <template #icon>
              <ArrowLeftOutlined />
            </template>
            返回映射集列表
          </AButton>
        </div>
        <div class="flex items-center gap-3">
          <ADivider type="vertical" />
          <div>
            <ATag color="blue" class="mr-2">映射集详情</ATag>
            <span class="text-lg font-medium">{{ mappingSetName }}</span>
            <span class="ml-2 text-sm text-gray-500">ID: {{ mappingSetId }}</span>
          </div>
        </div>
      </div>
    </ACard>

    <ARow :gutter="16">
      <!-- 左侧产品树 -->
      <ACol :xs="24" :lg="10">
        <ACard title="产品树" class="h-full">
          <template #extra>
            <ASpace>
              <AButton size="small" type="primary" @click="handleScanProducts">
                <template #icon>
                  <icon-carbon:search />
                </template>
                扫描实体类
              </AButton>
              <AButton size="small" @click="loadProductTree">
                <template #icon>
                  <ReloadOutlined />
                </template>
                刷新
              </AButton>
              <AButton size="small" @click="expandAll">展开全部</AButton>
              <AButton size="small" @click="collapseAll">收起全部</AButton>
            </ASpace>
          </template>
          <Tree
            v-if="treeData.length > 0"
            :tree-data="treeData"
            :field-names="{
              children: 'children',
              title: 'className',
              key: 'className'
            }"
            class="product-tree"
            show-line
            :expanded-keys="expandedKeys"
            @expand="onExpand"
            @select="onTreeSelect"
          >
            <template #title="{ className, category, isLeaf }">
              <div class="flex items-center gap-2">
                <ATag
                  v-if="!isLeaf"
                  :color="
                    category === 'fx' ? 'blue' : category === 'bond' ? 'green' : category === 'pm' ? 'purple' : 'orange'
                  "
                  size="small"
                >
                  {{ category }}
                </ATag>
                <div v-else class="flex items-center gap-2">
                  <span>{{ className }}</span>
                  <ATag v-if="!productMappingStatus[className]" color="red" size="small">未配置</ATag>
                  <ATag v-else color="green" size="small">已配置</ATag>
                </div>
              </div>
            </template>
          </Tree>
          <div v-else-if="!loading" class="py-8 text-center text-gray-500 dark:text-gray-400">
            <div>暂无产品数据</div>
            <div class="mt-2 text-sm">请检查后端服务是否正常</div>
          </div>
          <div v-else class="py-8 text-center text-gray-500 dark:text-gray-400">加载中...</div>
          <ADivider class="mb-1 mt-3"></ADivider>
          <!-- 统计信息 -->
          <div class="text-xs text-gray-500 dark:text-gray-400">
            <div class="grid grid-cols-2 gap-2">
              <div>总数: {{ treeData.length }}</div>
              <div>状态: {{ loading ? '加载中' : '已完成' }}</div>
            </div>
          </div>
        </ACard>
      </ACol>

      <!-- 右侧产品详情和模型管理 -->
      <ACol :xs="24" :lg="14">
        <div v-if="!selectedProduct" class="py-16 text-center text-gray-500 dark:text-gray-400">
          <div class="text-lg">请从左侧产品树中选择一个产品</div>
          <div class="mt-2 text-sm">选择后可以查看该产品的详细信息并配置模型映射</div>
        </div>

        <div v-else class="ASpace-y-4">
          <!-- 模型映射管理 -->
          <ACard title="模型映射管理" class="mt-1">
            <template #extra></template>

            <div v-if="modelLoading" class="py-8 text-center text-gray-500 dark:text-gray-400">加载模型列表中...</div>

            <div v-else-if="modelList.length === 0" class="py-8 text-center text-gray-500 dark:text-gray-400">
              <div>暂无可用模型</div>
              <div class="mt-2 text-sm">请检查后端模型服务</div>
            </div>

            <div v-else class="space-y-4">
              <!-- 显示已有映射关系 -->
              <div
                v-if="existingMappings.length > 0"
                class="mb-4 border border-blue-200 rounded bg-blue-50 p-3 dark:border-blue-700 dark:bg-gray-900"
              >
                <div class="mb-2 text-sm text-blue-800 font-medium dark:text-blue-300">
                  已绑定的模型 ({{ existingMappings.length }})：
                </div>
                <div class="flex flex-wrap gap-3">
                  <ATag
                    v-for="mapping in existingMappings"
                    :key="mapping.id"
                    color="blue"
                    size="small"
                    closable
                    @close="() => removeProductModelMapping(mapping)"
                  >
                    {{ getModelNameById(mapping.modelId) }}
                    <span v-if="mapping.enabled" class="ml-1 text-green-600">✓</span>
                    <span v-else class="ml-1 text-red-600">✗</span>
                    <AButton
                      v-if="parseConfigParams(mapping.configParams)"
                      type="link"
                      size="small"
                      class="ml-1 p-0"
                      @click="() => configureModelParameters(mapping.modelId)"
                    >
                      <SettingOutlined />
                    </AButton>
                  </ATag>
                </div>
                <div class="mt-2 text-xs text-gray-500 dark:text-gray-400">点击标签右侧的 × 可以解除绑定</div>
              </div>

              <!-- 配置产品-模型映射 -->
              <ADivider v-if="showConfigForm" orientation="left">配置产品-模型映射</ADivider>

              <div
                v-if="showConfigForm"
                class="border border-gray-200 rounded-lg bg-gray-50 p-4 dark:border-gray-700 dark:bg-gray-800"
              >
                <AForm :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
                  <!-- 基本信息 -->
                  <AFormItem label="产品" required>
                    <AInput :value="selectedProduct?.className" disabled />
                  </AFormItem>

                  <AFormItem label="模型" required>
                    <ASelect
                      v-if="!currentModelConfig"
                      v-model:value="modelConfigForm.modelId"
                      placeholder="请选择模型"
                      :allow-clear="true"
                      @change="onModelChange"
                    >
                      <ASelectOption v-for="model in modelList" :key="model.id" :value="model.id">
                        {{ model.name }}
                      </ASelectOption>
                    </ASelect>
                    <AInput v-else :value="currentModelConfig?.name" disabled />
                  </AFormItem>

                  <AFormItem label="求解器" required>
                    <ASelect
                      v-model:value="modelConfigForm.solver"
                      placeholder="请选择求解器"
                      @change="onModelOrSolverChange"
                    >
                      <ASelectOption v-for="solver in solverOptions" :key="solver.value" :value="solver.value">
                        <div>
                          <div>{{ solver.label }}</div>
                          <div style="font-size: 12px; color: #999">{{ solver.description }}</div>
                        </div>
                      </ASelectOption>
                    </ASelect>
                  </AFormItem>

                  <!-- 参数配置 -->
                  <template v-if="parameterFields.length > 0">
                    <ADivider orientation="left">参数配置</ADivider>

                    <template v-for="field in parameterFields" :key="field.key">
                      <AFormItem :label="field.label">
                        <template #extra>
                          <div style="font-size: 12px; color: #666">{{ field.description }}</div>
                        </template>

                        <!-- 数字输入 -->
                        <AInputNumber
                          v-if="field.type === 'number'"
                          v-model:value="modelConfigForm.parameters[field.key]"
                          :min="field.min"
                          :max="field.max"
                          :step="field.step || 1"
                          :precision="field.key === 'precision' ? 12 : 0"
                          style="width: 100%"
                        />

                        <!-- 布尔值选择 -->
                        <ASwitch
                          v-else-if="field.type === 'boolean'"
                          v-model:checked="modelConfigForm.parameters[field.key]"
                        />

                        <!-- 下拉选择 -->
                        <ASelect
                          v-else-if="field.type === 'select'"
                          v-model:value="modelConfigForm.parameters[field.key]"
                          style="width: 100%"
                        >
                          <ASelectOption v-for="option in field.options" :key="option.value" :value="option.value">
                            {{ option.label }}
                          </ASelectOption>
                        </ASelect>

                        <!-- 文本输入 -->
                        <AInput v-else v-model:value="modelConfigForm.parameters[field.key]" />
                      </AFormItem>
                    </template>
                  </template>

                  <!-- 操作按钮 -->
                  <AFormItem :wrapper-col="{ offset: 6, span: 18 }">
                    <ASpace>
                      <AButton type="primary" :loading="configModalLoading" @click="handleSaveModelConfig">
                        保存配置
                      </AButton>
                      <AButton @click="handleCancelConfig">取消</AButton>
                    </ASpace>
                  </AFormItem>
                </AForm>
              </div>

              <div v-else-if="existingMappings.length === 0" class="py-4 text-center">
                <AButton type="dashed" @click="showConfigurationForm">
                  <template #icon>
                    <PlusOutlined />
                  </template>
                  开始配置产品-模型映射
                </AButton>
              </div>

              <ADivider class="mb-1 mt-3"></ADivider>
              <!-- 统计信息 -->
              <div class="text-xs text-gray-500 dark:text-gray-400">
                <div class="grid grid-cols-1 gap-4 md:grid-cols-3">
                  <div>总模型数: {{ modelList.length }}</div>
                  <div>已选择: {{ selectedModelId ? 1 : 0 }}</div>
                  <div>映射状态: {{ selectedModelId ? '待保存' : '无选择' }}</div>
                </div>
              </div>
            </div>
          </ACard>
        </div>
      </ACol>
    </ARow>

    <!-- 模型配置模态框 - 已移除，配置功能已集成到页面中 -->
  </div>
</template>

<style scoped>
.product-tree-management {
  padding: 24px;
}

.product-tree {
  max-height: 600px;
  overflow-y: auto;
}

.model-list {
  max-height: 400px;
  overflow-y: auto;
  border: 1px solid #f0f0f091;
  border-radius: 6px;
}

.model-item {
  padding: 12px 16px;
  /* border-bottom: 1px solid #f0f0f0ae; */
  transition: background-color 0.2s;
}

.model-item:hover {
  background-color: #ffffff50;
}

.model-item:last-child {
  border-bottom: none;
}

/* 修复按钮图标与文字错位问题 */
:deep(.ant-btn) {
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

:deep(.ant-btn-icon) {
  margin-right: 4px;
}

@media (max-width: 768px) {
  .product-tree-management {
    padding: 16px;
  }

  .model-list {
    max-height: 300px;
  }
}
</style>
